package com.open.video.controller;

import com.alibaba.fastjson.JSONObject;
import com.open.capacity.common.model.SysCompany;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.video.model.VideoModel;
import com.open.video.service.VideoService;
import com.open.video.service.impl.FeignService;
import com.open.video.util.CommonResult;
import com.open.video.util.UploadVideoDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.MatrixParam;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
//注：请求pushVideo，生成路径点击就可观看视频
@RestController
@RequestMapping("/video")
public class VideoPushController {
    @Autowired
    VideoService videoService;

    @Autowired
    FeignService feignService;
    /**
     * 上传视屏并且保存视频到数据库
     * @param videoModel
     * @return
     */

    /**
     * @Description: 调用file-center上传文件
     * @Param: [file] 文件
     * @return: com.open.capacity.user.model.FileInfo  返回文件信息
     * @Author: bellweather
     * @Date: 2021/1/9
     */
//    @PostMapping("/upload")
//    public FileInfo updalods(@RequestPart("file")MultipartFile file){
//        FileInfo updload = feignService.updload(file);
//        return updload;
//    }



    @PostMapping("/pushVideo")
    public Result pushVideo(@RequestBody VideoModel videoModel) throws IOException {
        Base64.Decoder decoder = Base64.getDecoder();
        String index=videoModel.getFile().split(",")[1];
        byte[] decode = decoder.decode(index);
        //1:使用File类创建一个要操作的文件路径
        File file = new File("D:" + File.separator + "demo" + File.separator + videoModel.getFileName()+".mp4");
        if(!file.getParentFile().exists()){ //如果文件的目录不存在
            file.getParentFile().mkdirs(); //创建目录
        }

        //2: 实例化OutputString 对象
        OutputStream output = new FileOutputStream(file);
        output.write(decode);
        //4: 资源操作的最后必须关闭
        output.close();

        if(videoModel.getFileName().equals("")||videoModel.getFileName()==null){
            return Result.failed("文件名不能为空");
        }
//        else if(videoModel.getFileUrl().equals("")||videoModel.getFileUrl()==null){
//            return Result.failed("文件路径不能为空");
//        }
        else {
//            try {
//                Thread.sleep(6000);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            videoModel.setFileUrl(file.getPath());
            JSONObject result= UploadVideoDemo.UploadVideo(videoModel.getFileName(),videoModel.getFileUrl());
            String url=UploadVideoDemo.GetPlayInfo((String)result.get("vid"));
            String vid=(String)result.get("vid");
            VideoModel videoModel1=new VideoModel();
            videoModel1.setVid(vid);
            videoModel1.setFileUrl(url);
            videoModel1.setFileName(videoModel.getFileName());
            videoModel1.setDate(LocalDateTime.now().toString());
            videoModel1.setCompanyId(videoModel.getCompanyId());
            videoModel1.setType(videoModel.getType());
            //如果上传成功把数据保存在数据库
            if(url!=null){
                int results=videoService.addVideo(videoModel1);
            }
            return Result.succeed(videoModel1,"视频");
        }
    }

    /**
     * 根据vid删除aliyun以及数据库中的视屏数据
     * @param vid
     * @return
     */
    @RequestMapping("/deleteVideo")
    public Result deleteVideo(@RequestParam String vid){
        String result=UploadVideoDemo.deletesVideo(vid);
        if(result.equals("删除成功")){
            int results=videoService.deletesVideo(vid);
        }
        return Result.succeed(result,"删除成功");
    }

    /**
     * 展示所有视屏地址以及vid和名字
     * @return
     */
   @PostMapping("/selectAllVideo")
    public Result selectAllVideo(@RequestParam Map<String,Object>params){
       List<VideoModel>list=videoService.selectAllVideo(params);
       return Result.succeed(list,"所有视屏");
   }

    /**
     * 根据id查找视屏信息,包括日期，vid，名字，url等
     * @param id
     * @return
     */
    @PostMapping("/selectVideoById")
    public Result selectVideoById(@RequestParam Integer id){
       VideoModel videoModel=videoService.selectVideoById(id);
        return Result.succeed(videoModel,"查找视频");
    }
    /**fileName date时间段查询 type
     * 根据字段名模糊查找视频,分页前端需要封装pageModel对象的page和limit参数{
     *     "pageModel":{ "page":"0", "limit":"4"}，不能为空，为空需设置默认值
     * }
     */
    @PostMapping("/findSomeVideo")
    public PageResult findSomeVideo(@RequestParam Map<String,Object>params){
        List<VideoModel> list=videoService.findSomeVideo(params);
        return PageResult.<VideoModel>builder().code(0).data(list).count((long) list.size()).build();
    }

    /**
     * 视屏按照发布日期降序排序，查看最新发布视屏
     * @return
     */
    @PostMapping("/descVideo")
    public PageResult<VideoModel> DescVideo(){
        List<VideoModel> list=videoService.DescVideo();
        return PageResult.<VideoModel>builder().code(0).data(list).count((long) list.size()).build();
    }

    /**
     * 修改视频接口
     */
    @PostMapping("/edit")
    public Result editVideo(@RequestBody VideoModel videoModel){
        int result=videoService.updateVideo(videoModel);
        return Result.succeed(result,"修改成功");
    }

    /**
     * 查询公司
     * @return
     */
    @PostMapping("/selectCompany")
    public Result selectCompany(){
        List<SysCompany>companies=new ArrayList<>();
        companies=videoService.selectCompany();
        return Result.succeed(companies,"查询成功");
    }

}
